{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2023 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# single_machine_scheduling_with_setup_release_due_dates_sat"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/examples/single_machine_scheduling_with_setup_release_due_dates_sat.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/python/single_machine_scheduling_with_setup_release_due_dates_sat.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "Single machine jobshop with setup times, release dates and due dates.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Sequence\n",
    "from ortools.sat.colab import flags\n",
    "from google.protobuf import text_format\n",
    "from ortools.sat.python import cp_model\n",
    "\n",
    "# ----------------------------------------------------------------------------\n",
    "# Command line arguments.\n",
    "_OUTPUT_PROTO = flags.define_string(\n",
    "    \"output_proto\", \"\", \"Output file to write the cp_model proto to.\"\n",
    ")\n",
    "_PARAMS = flags.define_string(\n",
    "    \"params\",\n",
    "    \"num_search_workers:16,log_search_progress:true,max_time_in_seconds:45\",\n",
    "    \"Sat solver parameters.\",\n",
    ")\n",
    "_PREPROCESS = flags.define_bool(\n",
    "    \"--preprocess_times\", True, \"Preprocess setup times and durations\"\n",
    ")\n",
    "\n",
    "\n",
    "# ----------------------------------------------------------------------------\n",
    "# Intermediate solution printer\n",
    "class SolutionPrinter(cp_model.CpSolverSolutionCallback):\n",
    "    \"\"\"Print intermediate solutions.\"\"\"\n",
    "\n",
    "    def __init__(self):\n",
    "        cp_model.CpSolverSolutionCallback.__init__(self)\n",
    "        self.__solution_count = 0\n",
    "\n",
    "    def on_solution_callback(self):\n",
    "        \"\"\"Called after each new solution found.\"\"\"\n",
    "        print(\n",
    "            \"Solution %i, time = %f s, objective = %i\"\n",
    "            % (self.__solution_count, self.WallTime(), self.ObjectiveValue())\n",
    "        )\n",
    "        self.__solution_count += 1\n",
    "\n",
    "\n",
    "def single_machine_scheduling():\n",
    "    \"\"\"Solves a complex single machine jobshop scheduling problem.\"\"\"\n",
    "\n",
    "    parameters = _PARAMS.value\n",
    "    output_proto_file = _OUTPUT_PROTO.value\n",
    "\n",
    "    # ----------------------------------------------------------------------------\n",
    "    # Data.\n",
    "\n",
    "    job_durations = [\n",
    "        2546,\n",
    "        8589,\n",
    "        5953,\n",
    "        3710,\n",
    "        3630,\n",
    "        3016,\n",
    "        4148,\n",
    "        8706,\n",
    "        1604,\n",
    "        5502,\n",
    "        9983,\n",
    "        6209,\n",
    "        9920,\n",
    "        7860,\n",
    "        2176,\n",
    "    ]\n",
    "\n",
    "    setup_times = [\n",
    "        [\n",
    "            3559,\n",
    "            1638,\n",
    "            2000,\n",
    "            3676,\n",
    "            2741,\n",
    "            2439,\n",
    "            2406,\n",
    "            1526,\n",
    "            1600,\n",
    "            3356,\n",
    "            4324,\n",
    "            1923,\n",
    "            3663,\n",
    "            4103,\n",
    "            2215,\n",
    "        ],\n",
    "        [\n",
    "            1442,\n",
    "            3010,\n",
    "            1641,\n",
    "            4490,\n",
    "            2060,\n",
    "            2143,\n",
    "            3376,\n",
    "            3891,\n",
    "            3513,\n",
    "            2855,\n",
    "            2653,\n",
    "            1471,\n",
    "            2257,\n",
    "            1186,\n",
    "            2354,\n",
    "        ],\n",
    "        [\n",
    "            1728,\n",
    "            3583,\n",
    "            3243,\n",
    "            4080,\n",
    "            2191,\n",
    "            3644,\n",
    "            4023,\n",
    "            3510,\n",
    "            2135,\n",
    "            1346,\n",
    "            1410,\n",
    "            3565,\n",
    "            3181,\n",
    "            1126,\n",
    "            4169,\n",
    "        ],\n",
    "        [\n",
    "            1291,\n",
    "            1703,\n",
    "            3103,\n",
    "            4001,\n",
    "            1712,\n",
    "            1137,\n",
    "            3341,\n",
    "            3485,\n",
    "            2557,\n",
    "            2435,\n",
    "            1972,\n",
    "            1986,\n",
    "            1522,\n",
    "            4734,\n",
    "            2520,\n",
    "        ],\n",
    "        [\n",
    "            4134,\n",
    "            2200,\n",
    "            1502,\n",
    "            3995,\n",
    "            1277,\n",
    "            1808,\n",
    "            1020,\n",
    "            2078,\n",
    "            2999,\n",
    "            1605,\n",
    "            1697,\n",
    "            2323,\n",
    "            2268,\n",
    "            2288,\n",
    "            4856,\n",
    "        ],\n",
    "        [\n",
    "            4974,\n",
    "            2480,\n",
    "            2492,\n",
    "            4088,\n",
    "            2587,\n",
    "            4652,\n",
    "            1478,\n",
    "            3942,\n",
    "            1222,\n",
    "            3305,\n",
    "            1206,\n",
    "            1024,\n",
    "            2605,\n",
    "            3080,\n",
    "            3516,\n",
    "        ],\n",
    "        [\n",
    "            1903,\n",
    "            2584,\n",
    "            2104,\n",
    "            1609,\n",
    "            4745,\n",
    "            2691,\n",
    "            1539,\n",
    "            2544,\n",
    "            2499,\n",
    "            2074,\n",
    "            4793,\n",
    "            1756,\n",
    "            2190,\n",
    "            1298,\n",
    "            2605,\n",
    "        ],\n",
    "        [\n",
    "            1407,\n",
    "            2536,\n",
    "            2296,\n",
    "            1769,\n",
    "            1449,\n",
    "            3386,\n",
    "            3046,\n",
    "            1180,\n",
    "            4132,\n",
    "            4783,\n",
    "            3386,\n",
    "            3429,\n",
    "            2450,\n",
    "            3376,\n",
    "            3719,\n",
    "        ],\n",
    "        [\n",
    "            3026,\n",
    "            1637,\n",
    "            3628,\n",
    "            3096,\n",
    "            1498,\n",
    "            4947,\n",
    "            1912,\n",
    "            3703,\n",
    "            4107,\n",
    "            4730,\n",
    "            1805,\n",
    "            2189,\n",
    "            1789,\n",
    "            1985,\n",
    "            3586,\n",
    "        ],\n",
    "        [\n",
    "            3940,\n",
    "            1342,\n",
    "            1601,\n",
    "            2737,\n",
    "            1748,\n",
    "            3771,\n",
    "            4052,\n",
    "            1619,\n",
    "            2558,\n",
    "            3782,\n",
    "            4383,\n",
    "            3451,\n",
    "            4904,\n",
    "            1108,\n",
    "            1750,\n",
    "        ],\n",
    "        [\n",
    "            1348,\n",
    "            3162,\n",
    "            1507,\n",
    "            3936,\n",
    "            1453,\n",
    "            2953,\n",
    "            4182,\n",
    "            2968,\n",
    "            3134,\n",
    "            1042,\n",
    "            3175,\n",
    "            2805,\n",
    "            4901,\n",
    "            1735,\n",
    "            1654,\n",
    "        ],\n",
    "        [\n",
    "            1099,\n",
    "            1711,\n",
    "            1245,\n",
    "            1067,\n",
    "            4343,\n",
    "            3407,\n",
    "            1108,\n",
    "            1784,\n",
    "            4803,\n",
    "            2342,\n",
    "            3377,\n",
    "            2037,\n",
    "            3563,\n",
    "            1621,\n",
    "            2840,\n",
    "        ],\n",
    "        [\n",
    "            2573,\n",
    "            4222,\n",
    "            3164,\n",
    "            2563,\n",
    "            3231,\n",
    "            4731,\n",
    "            2395,\n",
    "            1033,\n",
    "            4795,\n",
    "            3288,\n",
    "            2335,\n",
    "            4935,\n",
    "            4066,\n",
    "            1440,\n",
    "            4979,\n",
    "        ],\n",
    "        [\n",
    "            3321,\n",
    "            1666,\n",
    "            3573,\n",
    "            2377,\n",
    "            4649,\n",
    "            4600,\n",
    "            1065,\n",
    "            2475,\n",
    "            3658,\n",
    "            3374,\n",
    "            1138,\n",
    "            4367,\n",
    "            4728,\n",
    "            3032,\n",
    "            2198,\n",
    "        ],\n",
    "        [\n",
    "            2986,\n",
    "            1180,\n",
    "            4095,\n",
    "            3132,\n",
    "            3987,\n",
    "            3880,\n",
    "            3526,\n",
    "            1460,\n",
    "            4885,\n",
    "            3827,\n",
    "            4945,\n",
    "            4419,\n",
    "            3486,\n",
    "            3805,\n",
    "            3804,\n",
    "        ],\n",
    "        [\n",
    "            4163,\n",
    "            3441,\n",
    "            1217,\n",
    "            2941,\n",
    "            1210,\n",
    "            3794,\n",
    "            1779,\n",
    "            1904,\n",
    "            4255,\n",
    "            4967,\n",
    "            4003,\n",
    "            3873,\n",
    "            1002,\n",
    "            2055,\n",
    "            4295,\n",
    "        ],\n",
    "    ]\n",
    "\n",
    "    due_dates = [\n",
    "        -1,\n",
    "        -1,\n",
    "        28569,\n",
    "        -1,\n",
    "        98104,\n",
    "        27644,\n",
    "        55274,\n",
    "        57364,\n",
    "        -1,\n",
    "        -1,\n",
    "        60875,\n",
    "        96637,\n",
    "        77888,\n",
    "        -1,\n",
    "        -1,\n",
    "    ]\n",
    "    release_dates = [0, 0, 0, 0, 19380, 0, 0, 48657, 0, 27932, 0, 0, 24876, 0, 0]\n",
    "\n",
    "    precedences = [(0, 2), (1, 2)]\n",
    "\n",
    "    # ----------------------------------------------------------------------------\n",
    "    # Helper data.\n",
    "    num_jobs = len(job_durations)\n",
    "    all_jobs = range(num_jobs)\n",
    "\n",
    "    # ----------------------------------------------------------------------------\n",
    "    # Preprocess.\n",
    "    if _PREPROCESS.value:\n",
    "        for job_id in all_jobs:\n",
    "            min_incoming_setup = min(\n",
    "                setup_times[j][job_id] for j in range(num_jobs + 1)\n",
    "            )\n",
    "            if release_dates[job_id] != 0:\n",
    "                min_incoming_setup = min(min_incoming_setup, release_dates[job_id])\n",
    "            if min_incoming_setup == 0:\n",
    "                continue\n",
    "\n",
    "            print(\n",
    "                \"job %i has a min incoming setup of %i\" % (job_id, min_incoming_setup)\n",
    "            )\n",
    "            # We can transfer some setup times to the duration of the job.\n",
    "            job_durations[job_id] += min_incoming_setup\n",
    "            # Decrease corresponding incoming setup times.\n",
    "            for j in range(num_jobs + 1):\n",
    "                setup_times[j][job_id] -= min_incoming_setup\n",
    "            # Adjust release dates if needed.\n",
    "            if release_dates[job_id] != 0:\n",
    "                release_dates[job_id] -= min_incoming_setup\n",
    "\n",
    "    # ----------------------------------------------------------------------------\n",
    "    # Model.\n",
    "    model = cp_model.CpModel()\n",
    "\n",
    "    # ----------------------------------------------------------------------------\n",
    "    # Compute a maximum makespan greedily.\n",
    "    horizon = sum(job_durations) + sum(\n",
    "        max(setup_times[i][j] for i in range(num_jobs + 1)) for j in range(num_jobs)\n",
    "    )\n",
    "    print(\"Greedy horizon =\", horizon)\n",
    "\n",
    "    # ----------------------------------------------------------------------------\n",
    "    # Global storage of variables.\n",
    "    intervals = []\n",
    "    starts = []\n",
    "    ends = []\n",
    "\n",
    "    # ----------------------------------------------------------------------------\n",
    "    # Scan the jobs and create the relevant variables and intervals.\n",
    "    for job_id in all_jobs:\n",
    "        duration = job_durations[job_id]\n",
    "        release_date = release_dates[job_id]\n",
    "        due_date = due_dates[job_id] if due_dates[job_id] != -1 else horizon\n",
    "        print(\n",
    "            \"job %2i: start = %5i, duration = %4i, end = %6i\"\n",
    "            % (job_id, release_date, duration, due_date)\n",
    "        )\n",
    "        name_suffix = \"_%i\" % job_id\n",
    "        start = model.NewIntVar(release_date, due_date, \"s\" + name_suffix)\n",
    "        end = model.NewIntVar(release_date, due_date, \"e\" + name_suffix)\n",
    "        interval = model.NewIntervalVar(start, duration, end, \"i\" + name_suffix)\n",
    "        starts.append(start)\n",
    "        ends.append(end)\n",
    "        intervals.append(interval)\n",
    "\n",
    "    # No overlap constraint.\n",
    "    model.AddNoOverlap(intervals)\n",
    "\n",
    "    # ----------------------------------------------------------------------------\n",
    "    # Transition times using a circuit constraint.\n",
    "    arcs = []\n",
    "    for i in all_jobs:\n",
    "        # Initial arc from the dummy node (0) to a task.\n",
    "        start_lit = model.NewBoolVar(\"\")\n",
    "        arcs.append((0, i + 1, start_lit))\n",
    "        # If this task is the first, set to minimum starting time.\n",
    "        min_start_time = max(release_dates[i], setup_times[0][i])\n",
    "        model.Add(starts[i] == min_start_time).OnlyEnforceIf(start_lit)\n",
    "        # Final arc from an arc to the dummy node.\n",
    "        arcs.append((i + 1, 0, model.NewBoolVar(\"\")))\n",
    "\n",
    "        for j in all_jobs:\n",
    "            if i == j:\n",
    "                continue\n",
    "\n",
    "            lit = model.NewBoolVar(\"%i follows %i\" % (j, i))\n",
    "            arcs.append((i + 1, j + 1, lit))\n",
    "\n",
    "            # We add the reified precedence to link the literal with the times of the\n",
    "            # two tasks.\n",
    "            # If release_dates[j] == 0, we can strenghten this precedence into an\n",
    "            # equality as we are minimizing the makespan.\n",
    "            if release_dates[j] == 0:\n",
    "                model.Add(starts[j] == ends[i] + setup_times[i + 1][j]).OnlyEnforceIf(\n",
    "                    lit\n",
    "                )\n",
    "            else:\n",
    "                model.Add(starts[j] >= ends[i] + setup_times[i + 1][j]).OnlyEnforceIf(\n",
    "                    lit\n",
    "                )\n",
    "\n",
    "    model.AddCircuit(arcs)\n",
    "\n",
    "    # ----------------------------------------------------------------------------\n",
    "    # Precedences.\n",
    "    for before, after in precedences:\n",
    "        print(\"job %i is after job %i\" % (after, before))\n",
    "        model.Add(ends[before] <= starts[after])\n",
    "\n",
    "    # ----------------------------------------------------------------------------\n",
    "    # Objective.\n",
    "    makespan = model.NewIntVar(0, horizon, \"makespan\")\n",
    "    model.AddMaxEquality(makespan, ends)\n",
    "    model.Minimize(makespan)\n",
    "\n",
    "    # ----------------------------------------------------------------------------\n",
    "    # Write problem to file.\n",
    "    if output_proto_file:\n",
    "        print(\"Writing proto to %s\" % output_proto_file)\n",
    "        with open(output_proto_file, \"w\") as text_file:\n",
    "            text_file.write(str(model))\n",
    "\n",
    "    # ----------------------------------------------------------------------------\n",
    "    # Solve.\n",
    "    solver = cp_model.CpSolver()\n",
    "    if parameters:\n",
    "        text_format.Parse(parameters, solver.parameters)\n",
    "    solution_printer = SolutionPrinter()\n",
    "    solver.Solve(model, solution_printer)\n",
    "    for job_id in all_jobs:\n",
    "        print(\n",
    "            \"job %i starts at %i end ends at %i\"\n",
    "            % (job_id, solver.Value(starts[job_id]), solver.Value(ends[job_id]))\n",
    "        )\n",
    "\n",
    "\n",
    "def main(argv: Sequence[str]) -> None:\n",
    "    if len(argv) > 1:\n",
    "        raise app.UsageError(\"Too many command-line arguments.\")\n",
    "    single_machine_scheduling()\n",
    "\n",
    "\n",
    "main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}
